package com.pay.utils.validate.annotation;

import com.pay.utils.validate.vali_util.ValidateCodeEnum;
import com.pay.utils.validate.vali_util.ValidateConstants;
import com.pay.utils.validate.vali_util.ValidateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;


/**
 * 注解RemoveEmptyOrNullParamter aop
 *
 * @author MENG
 * @version 2017/7/13
 * @see
 */
@Aspect
@Component
public class ValidateParameterAspect
{
    private static Logger logger = LoggerFactory.getLogger(ValidateParameterAspect.class);

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.pay.utils.validate.annotation.ValidateParameter)")
    public void pointCutMethod()
    {
    }

    /**
     * 环绕
     * @param
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("pointCutMethod()")
    public Object Around(ProceedingJoinPoint pjp) throws Throwable
    {
        //参数值
        Object[] objects = pjp.getArgs();

        Object returnObject = null;

        for(Object object : objects)
        {
            Method mothod = null;

            try
            {
                //当前参数对象是否继承了 BaseValidate 类
                mothod = object.getClass().getMethod(ValidateConstants.BASE_VALIDATE_METHOD_NAME);
            }
            catch (NoSuchMethodException e)
            {
                continue;
            }

            Map<String,Object> resultMap = (Map<String, Object>)mothod.invoke(object);

            if(!resultMap.get(ValidateConstants.RESULT_CODE).equals(ValidateConstants.RESULT_SUCCESS_CODE))
            {
                return resultMap;
            }

        }

        try
        {
            returnObject = pjp.proceed(pjp.getArgs());
        }
        catch (Exception e)
        {
            logger.error("",e);

            //表示函数 RequestBody 注解 错误 json参数没有正确的转换成实体类
            return ValidateUtil.returnError(ValidateCodeEnum.SYSTEM_ERROR);
        }

        return returnObject;

    }

}
